//
//  WBStatusViewModel.swift
//  weibo
//
//  Created by 李海超 on 2017/5/30.
//  Copyright © 2017年 lihaichao. All rights reserved.
//

import Foundation







//最大上拉次数,为了防止上拉到没数据时，多次刷新时accessToken被锁定
private let maxPullCount = 3

class WBStatusViewModel {
    
    lazy var staticList = [WBStatuses]()
    
    //当前上拉次数
    private var currentPullCount = 0
    
    /**
     将请求回来的数据转化为模型加到模型数组中
     
     - parameter complete: <#complete description#>
     */
    func loadStatus(pullup:Bool,complete:@escaping (Bool,Bool)->()) {
        
        
        if currentPullCount>maxPullCount{
            
            complete(true, false)
            
            return
        }
        
        
        let since_id = pullup ? 0 : staticList.first?.id ?? 0
        let max_id = !pullup ? 0 : staticList.last?.id ?? 0
        
            //请求数据
            WBNetworkManager.shared.statusList(since_id: since_id,max_id: max_id) { (list, IsSuccess) in
          
            //转化为数组
             guard let array = NSArray.yy_modelArray(with: WBStatuses.self, json: list) as? [WBStatuses]
                else{
                    
                   complete(IsSuccess,false)
                    
                    return
                }
                
                print("刷新了\(array.count)条数据")
                
                
                if pullup{
                    self.staticList += array
                }else{
                    //拼接数据
                    self.staticList = array + self.staticList
                
                }
                
                if pullup && array.count == 0{
                    
                    self.currentPullCount += 1
                    
                    complete(IsSuccess,false)
                    
                }else{
                    complete(IsSuccess,true)
                }
                
                

            
            
        }
    }
    
}
